<template>
  <div class="mask">
    <div class="container"></div>
  </div>
</template>

<script>
import { mapState, mapActions } from "Vuex";
import { decode } from "punycode";
import user from "api/user";
import common from "utilMethods/common";

export default {
  name: "Authorization",
  data() {
    return {
      temp: "",
    };
  },
  computed: {
    ...mapState({
      openId: (state) => state.user.openId,
      userType: (state) => state.user.userType,
      headImgUrl: (state) => state.user.headImgUrl,
    }),
  },
  mounted() {
    this.jumpToSpecificPage();
  },
  methods: {
    ...mapActions("user", [
      "setOpenId",
      "setToken",
      "setHeadImgUrl",
      "setUserInfo",
      "setUserType",
    ]),
    async getParams() {
      // 获取headImgUrl
      let headImgUrl_Authorization = common.getValFromUrl(null, "headImgUrl");
      this.temp = await user.getUserInfo();
      if (headImgUrl_Authorization === false) {
        //尝试从数据库中查询到头像地址
        
        if (this.temp.code == 1) {
          if (
            this.temp.data.detail.avatar != null &&
            this.temp.data.detail.avatar !== "false"
          ) {
            headImgUrl_Authorization = this.temp.data.detail.avatar;
          } else {
            headImgUrl_Authorization = "@/../static/img/user.png";
          }
        } else {
          headImgUrl_Authorization = "@/../static/img/user.png";
        }
      } else {
        headImgUrl_Authorization = decodeURIComponent(headImgUrl_Authorization);
      }
      this.setHeadImgUrl(headImgUrl_Authorization);
      await this.storeUserInfoLocal();
    },

    // 根据接口返回信息跳转到相应页面
    async jumpToSpecificPage() {
      // 获取openId
      this.setOpenId(common.getValFromUrl(null, "openid"));
      const result = await user.postUserLogin({ openid: this.openId });
      if (result.code == 1) {
        this.setToken(result.data.token);
        await this.getParams();
        //将用户的身份存入store
        this.setUserType(result.data.type);
        let pageName = common.getValFromUrl(null, "pageName");
        if (pageName != false) {
          this.$router.push({ name: pageName });
        } else {
          this.$router.push({ name: "U_view_all" });
        }
      } else {
        this.$router.push({ name: "Register" });
      }
    },

    async storeUserInfoLocal() {
      if (this.temp.code == 1) {
        this.setUserInfo(this.temp.data);
        if (this.headImgUrl !== this.temp.data.detail.avatar) {
          let tempUserInfo = this.temp.data;
          tempUserInfo.detail.avatar = this.headImgUrl;
          const res = await user.postUserPersonalInfo(tempUserInfo);
        }
      }
    },
  },
};
</script>
<style scoped>
.mask {
  width: 100%;
  height: 100%;
  margin-top: 50px;
  background: rgba(255, 255, 255, 0.8);
  position: fixed;
  left: 0;
  top: 0;
  z-index: 200;
  display: flex;
}
.container {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
</style>
